package com.qf.mybatisDemo_03.until;

import com.qf.mybatisDemo_03.entity.Book;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 刘欣
 * @createTime 2022/12/23 23:58
 * @description
 */
public class ReadAndWriteUtil {
    private static BufferedWriter writer;
    private static BufferedReader reader;

    /**
     * 创建文件初始化writer与reader
     */
    static {
        File file = FileUtil.getFile();
        try {
            writer = new BufferedWriter(new FileWriter(file.getAbsolutePath(), true));
            reader = new BufferedReader(new FileReader(file.getAbsolutePath()));
            System.out.println(reader);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量写入book
     *
     * @param books
     * @throws IOException
     */
    public static void writeBatch(List<Book> books) throws IOException {
        if (books.size() > 0) {
            for (Book book : books) {
                String cvs = book.toCvsStr();
                writer.write(cvs);
                writer.newLine();
                writer.flush();
            }
        }
    }

    /**
     * 批量读取book
     *
     * @param batchNum
     * @return
     * @throws Exception
     */
    public static List<Book> readBatch(Integer batchNum) throws Exception {
        List<Book> books = new ArrayList<>();
        String line = "";
        while ((line = reader.readLine()) != null) {
            books.add(Book.cvsToBook(line));
            if (books.size() == batchNum) {
                return books;
            }
        }
        return books;
    }

    /**
     * 关闭输出流
     */
    public static void closeWrite() {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭输入流
     */
    public static void closeRead() {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
